package cn.zhuama.system.service.impl;

import cn.zhuama.system.domain.Menu;
import cn.zhuama.system.mapper.MenuMapper;
import cn.zhuama.system.mapper.RoleMenuMapper;
import cn.zhuama.system.service.IMenuService;
import cn.zhuama.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.ElementType;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务实现类：
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private MenuMapper  menuMapper;
    @Override
    @Transactional
    public void removeById(Long id) {
        roleMenuMapper.deleteByMenuId(id);
        super.removeById(id);
    }

    @Override
    public List<Menu> menuTree() {
        List<Menu> menus = menuMapper.selectAll();

        Map<Long, Menu> map = menus.stream()
                .collect(Collectors.toMap(Menu::getId, menu -> menu));

        List<Menu> menuTree = new ArrayList<>();
        for (Menu menu: menus) {
            //如果是顶级部门 - 就添加到部门数
            if(menu.getParentId() == null){
                menuTree.add(menu);
            }else{//有父级部门
                //获取当前部门的父部门id
                Long parent_id = menu.getParentId();
                //根据父部门id获取父部门
                Menu m = map.get(parent_id);
                //将自己添加到父部门的集合列表中
                m.getChildren().add(menu);
            }
        }
        return menuTree;
    }

    @Override
    public List<Menu> loadMenuTreeByLoginInfoId(Long id) {
        List<Menu> menus =  menuMapper.selectByLoginInfoId(id);
        return menus;
    }
}
